<?php
// 包含数据库连接文件
include '../dbconnect.php';

// 检查所有必要的POST变量是否已设置
if (!isset($_POST['goodsname']) || !isset($_POST['type']) || !isset($_POST['oldprice']) || !isset($_POST['price']) || !isset($_POST['desc'])) {
    echo "所有字段都是必填的！";
    exit;
}

// 获取商品信息
$goods_name = $_POST['goodsname'];
$type = $_POST['type'];
$old_price = $_POST['oldprice'];
$description = $_POST['desc'];
$price = $_POST['price'];

// 保存图片
$file = $_FILES['picture']; // 得到传输的数据
$name = $file['name'];
$ext = strtolower(substr($name, strrpos($name, '.') + 1)); // 得到文件类型，并转化为小写
$allow_type = array('jpg', 'jpeg', 'gif', 'png'); // 定义允许上传的类型

// 判断文件类型是否被允许上传
if (!in_array($ext, $allow_type)) {
    echo "不允许的文件类型！";
    exit;
}

// 判断是否是通过HTTP POST上传的
if (!is_uploaded_file($file['tmp_name'])) {
    echo "非法上传！";
    exit;
}

$currentDir = dirname(__FILE__);
// 构建上传路径
$upload_path = $currentDir . '/uploads/'; // 获取当前目录并添加uploads子目录

// 确保uploads目录存在
if (!is_dir($upload_path)) {
    mkdir($upload_path, 0777, true);
}

// 保存图片
$file = $_FILES['picture']; // 得到传输的数据
$name = $file['name'];
$ext = strtolower(substr($name, strrpos($name, '.') + 1)); // 得到文件类型，并转化为小写
$allow_type = array('jpg', 'jpeg', 'gif', 'png'); // 定义允许上传的类型

// 判断文件类型是否被允许上传
if (!in_array($ext, $allow_type)) {
    echo "不允许的文件类型！";
    exit;
}

// 判断是否是通过HTTP POST上传的
if (!is_uploaded_file($file['tmp_name'])) {
    echo "非法上传！";
    exit;
}

/// 开始移动文件到相应的文件夹
if (move_uploaded_file($file['tmp_name'], $upload_path . $name)) {
    $base_url = 'http://localhost/BWD_Assignment/employee/';
    $picture_path = $base_url . 'uploads/' . $name;

    // 将完整的URL路径存储到数据库中
    include '../dbconnect.php';
    $sql = "INSERT INTO goods (GOODS_NAME, GOODS_TYPE, GOODS_PRICE, GOODS_DESC, GOODS_OLD_PRICE, GOODS_PICTURE) VALUES (?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssssss", $goods_name, $type, $price, $description, $old_price, $picture_path);

    if ($stmt->execute()) {
        echo "ADD SUCCESS！";
		header("Location: goodslist.php");
		
    } else {
        echo "ADD GOODS FAIL：" . $stmt->error;
    }

    $stmt->close();
    $conn->close();
} else {
    echo "UPLOAD FAIL！";
    exit;
}
?>